
const ServerResponse = require('@root/middlewares/resHandler');
const User = require('@root/models/user.model');

const Passport = require('@root/config/passport')

exports.login = async (ctx, next) => {
    return Passport.authenticate('local', (err, user, info, status) => {
        if (err) {
            ctx.body = {
                code: -1,
                msg: err
            }
        } else {
            if (user) {
                ctx.body = {
                    code: 0,
                    msg: '登录成功',
                    user: user.toAuthJSON()
                }
                return ctx.login(user)
            } else {
                ctx.body = {
                    code: 1,
                    msg: info
                }
            }
        }
    })(ctx, next)

}

exports.register = async ctx => {
    const { user: newUser } = ctx.request.body;
    const user = new User({
        method: 'local',
        username: newUser.username,
        local: {
            email: newUser.email,
            hash: newUser.password
        }
    });

    await user.save();

    return ctx.body = { user: user.toAuthJSON() };
}
exports.getUser = async ctx => {
    const user = await User.findById(ctx.state.user.id);
    return ctx.body = { user: user.toAuthJSON() };
}

exports.updateUser = async ctx => {

    const { user: newUser } = ctx.request.body;
    const user = await User.findById(ctx.state.user.id);

    if (typeof newUser.username !== 'undefined') {
        user.username = newUser.username;
    }
    if (typeof newUser.email !== 'undefined') {
        user[user.method].email = newUser.email;
    }
    if (typeof newUser.image !== 'undefined') {
        user.image = newUser.image;
    }
    if (typeof newUser.password !== 'undefined') {
        user[user.method].hash = newUser.password;
    }

    await user.save();

    ctx.body = { user: user.toAuthJSON() };
}
